#ifndef VERT_STRUCT
#define VERT_STRUCT
#include <UnityShaderUtilities.cginc>

//Camera
uniform float4x4 _CamFrustum; //相机视锥体矩阵
uniform float4x4 _CamToWorld; //摄像机空间到世界空间矩阵
// ShadowCam
float4x4 _shadow_cam_V;
float4x4 _shadow_cam_VP;

struct appdata
{
    float4 vertex : POSITION;
    float2 uv : TEXCOORD0;
};

struct v2f
{
    float2 uv : TEXCOORD0;
    float4 vertex : SV_POSITION;
    float4 ray : TEXCOORD1;
    float3 ori : TEXCOORD2;
    float debug : TEXCOORD3;
    float3 shadow_coord : TEXCOORD4;
};

v2f vert(appdata v, uint vid : SV_VertexID)
{
    v2f o;
    int index = 0;
    if (vid == 0) //用GL.Vertex3()的第三个量来作为索引标定顶点
        index = 3;
    else if (vid == 1)
        index = 0;
    else if (vid == 2)
        index = 1;
    else if (vid == 3)
        index = 2;
    v.vertex.z = 0;
    o.vertex = UnityObjectToClipPos(v.vertex);
    o.uv = v.uv;

    o.ray.xyz = _CamFrustum[index].xyz; //用顶点的位置取出对应视锥体的方向
    o.ray.xyz /= abs(o.ray.z);
#ifdef ORTHOGRAPHIC
    o.ori = mul(_CamToWorld, float4(o.ray.xy, 0, 1));
    // o.debug = o.ray.y;
    o.ray.xyz = mul(_CamToWorld, float4(0, 0, -1, 0));
#else
    // o.ori = mul(_CamToWorld, float4(0,0,0,1)); //发射射线的位置，世界空间
    o.ori = _WorldSpaceCameraPos; //发射射线的位置，世界空间
    o.debug = float4(o.ray.xyz,1.0);
    o.ray.xyz = mul(_CamToWorld, o.ray.xyz); //从相机坐标系到世界坐标系
    o.shadow_coord = mul(_shadow_cam_VP, mul(unity_ObjectToWorld, v.vertex));
    o.shadow_coord.z = -(mul(_shadow_cam_V, mul(unity_ObjectToWorld, v.vertex).z));
#endif

    // length(p) 和屏幕分辨率有关
    const float3 p = mul(_CamToWorld, float4(1, 0, 0, 0)); // float3默认被当成向量，w=0
    o.ray.w = 0.5 * length(p) / length(_ScreenParams.xy);
    return o;
}

#endif
